package com.exam.controller;

import com.exam.entity.Message;
import com.exam.entity.Student;
import com.exam.service.MessageService;
import com.exam.util.ZLConstants;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
public class MessageController {

    @Resource
    private MessageService messageService;

    @RequestMapping("/message")
    public Object MessageManagement(String op,String sno, String content,String mid,HttpSession session){
        if(op!=null && !"".equals(op)){
            if("stuReceive".equals(op)){//学生收信
                Student stu = (Student) session.getAttribute(ZLConstants.USER);
                List<Message> res = messageService.receiveMessagesByNo(stu.getSno());
                return res;
            }else if("stuSend".equals(op)){
                Student stu = (Student) session.getAttribute(ZLConstants.USER);
                int res = messageService.sendStuMessage(stu.getSno(),content);//学生发信
                return res;
            }else if("stuEverSend".equals(op)){
                Student stu = (Student) session.getAttribute(ZLConstants.USER);
                List<Message> res = messageService.getStuEverSendMessage(stu.getSno());//学生的历史发信
                return res;
            }else if("adminReceive".equals(op)){
                List<Message> res = messageService.getAllStuMessages();//管理员收反馈信
                return res;
            }else if("adminEverSend".equals(op)){
                List<Message> res = messageService.getAllAdminMessages();//管理员历史发信
                return res;
            }else if("multiSend".equals(op)){
                try{
                    messageService.sendToAllStu(content);//发送给所有学生
                    return "1";
                }catch (Exception e){
                    return "0";
                }
            }else if("singleSend".equals(op)){//发送给单个学生
                int res = messageService.sendToSingleStu(sno,content);
                if(res!=0){
                    return "1";
                }else{
                    return "0";
                }
            }else if("adminHasRead".equals(op)){
                int result = 0;
                String[] mids = mid.split(",");
                for (String id : mids){
                    if(messageService.adminHasRead(Integer.parseInt(id))==1){
                        result = 1;
                    }
                }
                return result;
            }else if("stuHasRead".equals(op)){
                if(messageService.stuHasRead(sno)==0){
                    return 0;
                }return 1;
            }
        }
        return null;
    }

    public void setMessageService(MessageService messageService) {
        this.messageService = messageService;
    }
}
